package com.azxcrm.project.monitor.upload.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSONObject;
import com.azxcrm.common.exception.base.BaseException;
import com.azxcrm.common.utils.RandomUtils;
import com.azxcrm.common.utils.StringUtils;
import com.azxcrm.framework.redis.template.service.RedisServiceImpl;

@Controller
public class UploadController {

	@Autowired
	private RedisServiceImpl redisServiceImpl;

	@Value("${azxcrm.savepath}")
	private String savepath;

	@RequestMapping(value = "/uploadInit", method = RequestMethod.GET)
	public String uploadInit() {
		return "monitor/upload/upload";
	}

	@RequestMapping("/upload")
	public @ResponseBody  synchronized  Object upload(HttpServletRequest request, String shortToken) throws BaseException {
		
		JSONObject object = new JSONObject();

		try {
			if (StringUtils.isNotEmpty(shortToken)) {

				CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
						request.getSession().getServletContext());
				// 判断 request 是否有文件上传,即多部分请求
				if (multipartResolver.isMultipart(request)) {
					// 转换成多部分request
					MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
					// 取得request中的所有文件名
					Iterator<String> iter = multiRequest.getFileNames();
					while (iter.hasNext()) {
						// 取得上传文件
						MultipartFile file = multiRequest.getFile(iter.next());
						// 数据封装操作 MultipartFile reqeust
						// 取得当前上传文件的文 件名称
						String myFileName = file.getOriginalFilename(); // 这里需要你对文件的处理哦
						String extensionName = myFileName.substring(myFileName.lastIndexOf(".") + 1);
						// 新的图片文件名 = 获取时间戳+"."图片扩展名
						String newFileName = new  SimpleDateFormat("yyyyMMdd").format(new Date())
								+ RandomUtils.randomCommon(0, 9, 5) + "." + extensionName;
						// 使用封装方法文件夹必须要先创建
						File fileDir = new File(savepath);
						if (!fileDir.exists()) {
							fileDir.mkdirs();
						}
						// 保存图片
						file.transferTo(new File(savepath + newFileName));

						// 将图片信息保存至Redis中，查看Redis中是否有已缓存的数据
						StringBuffer cacheData = new StringBuffer();
						String cacheKey = (String) redisServiceImpl.get(shortToken);

						if (StringUtils.isNotEmpty(cacheKey)) {
							// 有数据，持续添加
							cacheData.append(cacheKey).append(",").append(newFileName);
							redisServiceImpl.set(shortToken, cacheData.toString());
							redisServiceImpl.expire(shortToken, 600);
							/*try {
								Thread.sleep(600);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}*/
						} else {
							// 无数据初始化数据
							redisServiceImpl.set(shortToken, newFileName);
							// 过期时间单位为:s(秒)此处应与shiroSession有效期保持一致，统一为600s
							redisServiceImpl.expire(shortToken, 600);
							/*try {
								Thread.sleep(600);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}*/
						}

						object.put("fileName", newFileName);
						// logger.debug("图片上传：{}", JsonUtil.toString(map));
					}
					object.put("msg", 1);
				}
			} else {
				// 获取Token值失败
				object.put("msg", -2);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new BaseException("upload","get DataSource failed");
		}
		
		return object;
	}
}
